package name.flurl.android.tt_news4android;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.ImageView;

public class LazyImageView extends ImageView {

	private boolean mAlreadyLoaded = false;
	private Runnable mOnLoadCallback = null;

	private String mUrl;
	private Drawable mImage = null;

	boolean mExternalStorageAvailable = false;
	boolean mExternalStorageWriteable = false;

	// String mState = Environment.getExternalStorageState();

	public LazyImageView(Context context, String url, Runnable callback) {
		super(context);
		mUrl = url;
		mOnLoadCallback = callback;
		loadPlaceholderImage();
	}

	// public LazyImageView(GalleryActivity context, String url, Bitmap bitmap,
	// boolean alreadyLoaded) {
	// super(context);
	// mContext = context;
	// mUrl = url;
	// //mAlreadyLoaded = alreadyLoaded;
	// if (getDrawable() == null) {
	// setImageBitmap(bitmap);
	// mImage = new BitmapDrawable(bitmap);
	// }
	// }
	private class LoadImageTask extends AsyncTask<String, Integer, Integer> {
		protected Integer doInBackground(String... urls) {

			Log.i("POGA Events lazyload", "***");
			if (!mAlreadyLoaded) {

				try {
					loadImage();
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
			return 1;
		}

		protected void onPostExecute(Integer result) {
			mAlreadyLoaded = true;
			setImageDrawable(mImage);
			Log.i("tt_news", "after loading thread, b4 calling callback");
			mOnLoadCallback.run();
		}

	}

	public void load() {

		new LoadImageTask().execute("");

		// new Thread(new Runnable() {
		// public void run() {
		// Log.i("POGA Events lazyload", "***");
		// if (!mAlreadyLoaded) {
		//
		// try {
		// loadImage();
		// } catch (MalformedURLException e) {
		// e.printStackTrace();
		// return;
		// } catch (IOException e) {
		// e.printStackTrace();
		// return;
		// }
		// if (!LazyImageView.this.post(new Runnable() {
		// public void run() {
		// mAlreadyLoaded = true;
		// setImageDrawable(mImage);
		// Log
		// .i("tt_news",
		// "after loading thread, b4 calling callback");
		// mOnLoadCallback.run();
		// }
		// }))
		// Log.i("tt_news", "post unsuccessful");
		// else
		// Log.i("tt_news", "post successful");
		// }
		// }
		// }).start();
	}

	public void load(String url) {
		setmUrl(url);
		mAlreadyLoaded = false;
		load();
	}

	public Object fetch(String address) throws MalformedURLException,
			IOException {
		URL url = new URL(address);
		Object content = url.getContent();
		return content;
	}

	public void loadPlaceholderImage() {
		// BitmapDrawable drawable = (BitmapDrawable) getDrawable();
		// if (drawable != null) {
		// drawable.getBitmap().recycle();
		// }
		setImageResource(R.drawable.spinning_wheel);
	}

	private void loadImage() throws MalformedURLException, IOException {
		String filepath = Environment.getExternalStorageDirectory()
				.getAbsolutePath()
				+ "/at.postgarage.tt_news4android/images/";
		String filename = extractFilenameFromUrl();
		OutputStream outStream = null;

		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else {
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
		// try {
		// Thread.sleep(500);
		// } catch (InterruptedException e1) {
		// // TODO Auto-generated catch block
		// e1.printStackTrace();
		// }
		File file = new File(filepath, filename);
		Log.i("POGA LazyImageView filepath", file.getAbsolutePath());
		if (!file.exists()) {
			Log.i("POGA LazyImageView ", "cache miss");
			InputStream is = (InputStream) fetch(mUrl);
			mImage = Drawable.createFromStream(is, "src");
			if (mExternalStorageAvailable && mExternalStorageWriteable) {
				Log.i("POGA LazyImageView ", "ext storage available");
				new File(filepath).mkdirs();
				if (mImage != null) {
					Bitmap bm = ((BitmapDrawable) mImage).getBitmap();
					try {
						file.createNewFile();
						CompressFormat compressFormat = null;
						String ext = filename.substring(
								filename.lastIndexOf('.') + 1,
								filename.length()).toLowerCase();
						if (ext.equals("jpg")) {
							Log.i("tt_news jpg", "ext: " + ext);
							compressFormat = Bitmap.CompressFormat.JPEG;
						} else if (ext.equals("png")) {
							Log.i("tt_news png", "ext: " + ext);
							compressFormat = Bitmap.CompressFormat.PNG;
						} else
							Log.i("tt_news", "ext: " + ext);

						outStream = new FileOutputStream(file);
						bm.compress(compressFormat, 100, outStream);
						outStream.flush();
						outStream.close();

					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			} else
				Log.i("POGA LazyImageView ", "ext storage not available");
		} else {
			Log.i("POGA LazyImageView ", "cache hit");
			mImage = Drawable.createFromPath(file.getAbsolutePath());
			Log.i("POGA LazyImageView ", "after createfrompath");
		}
	}

	private String extractFilenameFromUrl() {

		File f = new File(mUrl.replaceAll("http://", ""));
		String fn = f.getName();
		Log.i("POGA filename", fn);
		return fn;
	}

	public void setmOnLoadCallback(Runnable r) {
		mOnLoadCallback = r;
	}

	public boolean ismAlreadyLoaded() {
		return mAlreadyLoaded;
	}

	private void setmAlreadyLoaded(boolean mAlreadyLoaded) {
		this.mAlreadyLoaded = mAlreadyLoaded;
	}

	public String getmUrl() {
		return mUrl;
	}

	public void setmUrl(String mUrl) {
		this.mUrl = mUrl;
	}

}
